package com.fenxiangtech.mall.web.controller.v1;

import com.fenxiangtech.mall.exception.ParameterMismatchException;
import com.fenxiangtech.mall.service.PayService;
import com.fenxiangtech.mall.wxpay.sdk.WXPayUtil;
import com.fenxiangtech.mall.dto.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller("payControllerV1")
@RequestMapping("/v1/pay")
public class PayController {

    private static final Logger log = LoggerFactory.getLogger(PayController.class);

    @Autowired
    private PayService payService;

    @PostMapping("/pre_pay")
    @ResponseBody
    public Result prePay(@RequestBody Map<String, String> data) {
        if (data.containsKey("oid")) {
            Long orderID = Long.parseLong(data.get("oid"));
            return payService.pay(orderID);
        } else {
            throw new ParameterMismatchException();
        }
    }

    @PostMapping("/notify")
    @ResponseBody
    public String receiveNotify(@RequestBody String strXML) {
        Map<String, String> data;
        Map<String, String> resultMap = new HashMap<>();
        try {
            data = WXPayUtil.xmlToMap(strXML);
            boolean success = payService.notifyProcess(data);
            if (success) {
                resultMap.put("return_code", "SUCCESS");
                resultMap.put("return_msg", "OK");
            } else {
                resultMap.put("return_code", "FAIL");
                resultMap.put("return_msg", data.get("return_msg"));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            resultMap.put("return_code", "FAIL");
            resultMap.put("return_msg", e.getMessage());
        }
        String xml = null;
        try {
            xml = WXPayUtil.mapToXml(resultMap);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return xml;
    }

}
